// pages/user-wage/user-wage.js
const app = getApp()

Page({
  data: {
    wageData: null,
    wageHistory: [],
    loading: true,
    refreshing: false,
    currentMonth: '',
    selectedMonth: '',
    totalWage: 0,
    totalQuantity: 0,
    averageWage: '0.00'
  },

  onLoad() {
    // 设置当前月份
    const now = new Date()
    const currentMonth = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}`
    
    this.setData({
      currentMonth: currentMonth,
      selectedMonth: currentMonth
    })
    
    this.loadWageData()
  },

  onShow() {
    this.loadWageData()
  },

  onPullDownRefresh() {
    this.setData({
      refreshing: true
    })
    this.loadWageData().then(() => {
      wx.stopPullDownRefresh()
      this.setData({
        refreshing: false
      })
    })
  },

  // 加载工资数据
  loadWageData() {
    this.setData({
      loading: true
    })

    return app.userRequest({
      url: '/getWageStats',
      data: {
        month: this.data.selectedMonth
      }
    }).then((res) => {
      console.log('工资数据API响应:', res)
      
      // 计算工资统计数据
      const wageData = res.data || {}
      const reports = wageData.reports || []
      
      const totalWage = wageData.total_wage || 0
      const totalQuantity = wageData.total_quantity || 0
      // 计算平均单价：总工资除以总数量
      const averageWage = totalQuantity > 0 ? (totalWage / totalQuantity).toFixed(2) : '0.00'
      
      console.log('计算后的数据:', {
        totalWage,
        totalQuantity,
        averageWage,
        reportsCount: reports.length
      })
      
      this.setData({
        wageData: reports, // 工资明细列表
        totalWage: parseFloat(totalWage), // 确保是数字类型
        totalQuantity: parseInt(totalQuantity), // 确保是数字类型
        averageWage: averageWage,
        loading: false
      })
      
      console.log('setData后的数据:', {
        totalWage: this.data.totalWage,
        totalQuantity: this.data.totalQuantity,
        averageWage: this.data.averageWage
      })
    }).catch((err) => {
      console.error('获取工资数据失败:', err)
      this.setData({
        loading: false
      })
      wx.showToast({
        title: '获取工资数据失败',
        icon: 'none'
      })
    })
  },

  // 加载工资历史
  loadWageHistory() {
    app.userRequest({
      url: '/getWageHistory'
    }).then((res) => {
      this.setData({
        wageHistory: res.data || []
      })
    }).catch((err) => {
      console.error('获取工资历史失败:', err)
    })
  },

  // 显示日期选择器
  showDatePicker() {
    console.log('showDatePicker 被调用')
    
    // 生成月份选项（最近6个月，因为showActionSheet最多支持6个选项）
    const months = []
    const currentDate = new Date()
    
    for (let i = 5; i >= 0; i--) {
      const date = new Date(currentDate.getFullYear(), currentDate.getMonth() - i, 1)
      const year = date.getFullYear()
      const month = date.getMonth() + 1
      const monthStr = `${year}-${String(month).padStart(2, '0')}`
      const monthNames = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
      const displayStr = `${year}年${monthNames[month - 1]}`
      months.push({
        value: monthStr,
        label: displayStr
      })
    }
    
    wx.showActionSheet({
      itemList: months.map(item => item.label),
      success: (res) => {
        const selectedMonth = months[res.tapIndex]
        console.log('选择的月份:', selectedMonth)
        this.setData({
          selectedMonth: selectedMonth.value
        })
        this.loadWageData()
      },
      fail: (err) => {
        console.error('选择月份失败:', err)
      }
    })
  },

  // 选择月份
  onMonthChange(e) {
    this.setData({
      selectedMonth: e.detail.value
    })
    this.loadWageData()
  },

  // 查看工资详情
  viewWageDetail(e) {
    const month = e.currentTarget.dataset.month
    this.setData({
      selectedMonth: month
    })
    this.loadWageData()
  },

  // 刷新工资数据
  refreshWage() {
    this.loadWageData()
  },

  // 导出工资单
  exportWage() {
    if (!this.data.wageData) {
      wx.showToast({
        title: '暂无工资数据',
        icon: 'none'
      })
      return
    }

    wx.showLoading({
      title: '导出中...'
    })

    app.userRequest({
      url: '/exportWage',
      method: 'POST',
      data: {
        month: this.data.selectedMonth
      }
    }).then((res) => {
      wx.hideLoading()
      if (res.data && res.data.download_url) {
        // 下载文件
        wx.downloadFile({
          url: res.data.download_url,
          success: (downloadRes) => {
            wx.openDocument({
              filePath: downloadRes.tempFilePath,
              success: () => {
                wx.showToast({
                  title: '导出成功',
                  icon: 'success'
                })
              }
            })
          }
        })
      } else {
        wx.showToast({
          title: '导出失败',
          icon: 'none'
        })
      }
    }).catch((err) => {
      wx.hideLoading()
      console.error('导出工资单失败:', err)
      wx.showToast({
        title: '导出失败',
        icon: 'none'
      })
    })
  }
}) 